//引入样式
require("../../assets/css/reset.css")
require('../../assets/css/normalize.css')
require('../../assets/fonts/iconfont.css')
require('./sports_course_play.less');

//引入模块
const axios = require('../../utils/axios.js');
const dom = require('../../utils/dom.js')

document.addEventListener('DOMContentLoaded', function () {
    //获取数据
    const fragments = JSON.parse(localStorage.getItem('courseData'));
    console.log(fragments);
    //获取节点
    const video = dom.get("#video");
    const pro = dom.get('#pro');
    let timer = null;
    let n = 0;
    let duration = 0;
    let startTime = Date.now()
    // 视频播放
    function play() {
        dom.get('#currentPage').textContent = n + 1;
        dom.get('#totalPages').textContent = fragments.length;
        dom.get("#video").src = axios.defaults.baseURL + fragments[n].videoUrl;
        dom.get('#desc').textContent = fragments[n].title;
        video.play();
        // 进度条
        timer = setInterval(function () {
            pro.style.width = (video.currentTime / video.duration) * 100 + '%';
        })
    }
    play();
    //视频连续播放，等上个视频播放完后自动开始下个视频的播放
    video.addEventListener('ended', function () {
        n++;
        if (n < fragments.length) {
            play();
        } else {
            n = fragments.length - 1;
        }
    })
    // 点击上个视频播放
    dom.get('#prev').addEventListener('click', function () {
        n--;
        if (n < 0) {
            n = 0;
        } else {
            play();
        }
    })
    // 点击下一个视频播放
    dom.get('#next').addEventListener('click', function () {
        n++;
        if (n < fragments.length) {
            play()
        } else {
            n = fragments.length - 1;
        }
    })
    //点击暂停停止播放 并弹出蒙层
    dom.get('#pasue').addEventListener('click', function () {
        video.pause();
        dom.get('#mask').style.display = 'block';
        dom.get('#box').style.display = 'flex';
        duration += Date.now() - startTime;
    })
    //点击继续训练，视频继续播放
    dom.get('.icon-bofang').addEventListener('click', function () {
        video.play();
        dom.get('#mask').style.display = 'none';
        dom.get('#box').style.display = 'none';
        startTime = Date.now();
    })
    //点击退出，视频播放结束上传数据并返回运动界面
    dom.get('.icon-guanji-').addEventListener('click', function () {
        duration = Math.floor(duration / 1000);
        let calorie = Math.ceil(duration * 1.57);
        axios.post('/api/exercise/save', {
            type: 2,
            duration,
            calorie
        }).then(res => {
            if (res.data.errno === 0) {
                alert('本次训练结束');
                location.href = 'sports_course.html';
            }
        })
    })
})
